<?php

namespace Addons\OaSystem\Model;
use Think\Model;

/**
 * OaSystem模型
 */
class OaEmpMsgModel extends Model
{
    var $template_ids = [
            'P-3lQGj8MWJJb5YcFZfU7Fckk_z5l0ykK7W-Mst52ME', // 0:公告
            'P65ehB6rExBmyZPeHuTEBXaWJRLLcO_wSzIfeHi2WLE', // 1:会议
            'WpUMHvCpUqDv9LLq_1JCec754c2ANpRHOjnv2oCv-RQ', // 2:督办
            'hmjk_OfSmyINZmThNAh2f4_9TIebp5rfWBQMrCJnizM', // 3:报销,加班,休假 待审批
            '8lW-BzeovfAZs8syz_0IE0fMcu-M0GM0xbhGqDMbqy0', // 4:报销,加班,休假 审批结果
            'auF-wCpshs3QVOYsL521lhkG1zWEa8l2gd6nCy24JMc',  // 5:食堂小卖部订单确认
            '5nGPxoQo0dh3H_sl1ud_KYy-z226ETE6gkykY6ZA1Ks', // 6:食堂小卖部订单创建
            '', // 7:小卖部通知
            ''  // 8:其它
        ];

    public function get_wxFormid ($openid) {
        $formIds = M('OaEmpWxformid')->where(array('openid'=>$openid))->select();
        $form_id = '';
        foreach ($formIds as $formId) {
            if ($formId['validtime'] < NOW_TIME){
                M('OaEmpWxformid')->where(array('id'=>$formId['id']))->delete();
            } else {
                $form_id = $formId['formid'];
                M('OaEmpWxformid')->where(array('id'=>$formId['id']))->delete();
                break;
            }
        }
        return $form_id;
    }

    /**
     * 生成消息数据
     *
     * @param int $type
     *        	消息类型
     *      0:公告
            1:会议
            2:督办
            3:报销审批
            4:加班审批
            5:休假审批
            6:食堂通知
            7:小卖部通知
            8:其它
     * @param int $receiver
     *        	收到消息的员工ID
     * @param array $content
     *        	是否为小程序Url*
    return True:  发送成功; False: 发送失败
     */
    private function generateSendMsgData($type,$formId,$receiver,$content,$notice_id=0){
        $typestr = ['公告','会议','督办','报销审批','加班审批','休假审批','食堂通知','小卖部通知','其它'];

        $data['type'] = $type;
        $data['emp_id'] = $receiver;
        if (!empty($notice_id)) { $data['noticeid'] = $notice_id; }
        $data['content'] = json_encode($content);
        $data['wx_formid'] = $formId;
        $data['time'] = NOW_TIME;
        return $data;
    }

    public function sendmsg($appid,$formId,$type,$receiver,$content,$noticid=0){
        $data = $this->generateSendMsgData($type,$formId,$receiver,$content,$noticid);
        $data['appid'] = $appid;
        $this->add($data);
        $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
        foreach ($usr_emps as $usr_emp) {
            if(!empty($usr_emp['openid'])){
                $this->sendReimburseMsg($usr_emp['openid'],$content,$formId);
            }
        }
        return true;
    }

    private function sendReimburseMsg($openid,$content,$formId,$is_sendWxMsg=false){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = 'oFSRQy8d0gSSL8k2S2Pr25YZ23rFez4rbfmnNXNoWSE';
        $param ['form_id'] = $formId;
        $param['data'] = $content;
        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            return $res;
        }
        return true;
    }

    private function sendApprovalResultWxMsg ($openid,$applyData,$formId) {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $types = [' ','加班审批结果','休假审批结果','报销审批结果'];

        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[4];
        $param ['form_id'] = $formId;
        $tmpData = D('OaApplicationView')->where(array('id'=>$applyData['id']))->find();
        if ($tmpData === false) {
            // $param ['page'] = '/pages/reimbures/index';
            $param ['page'] = 'pages/index/index';
        }else{
            // $param ['page'] = '/pages/reimburse/approvaldetails?readonly=true&comment=false&data='.json_encode($tmpData);
            $param ['page'] = 'pages/index/index';
        }

        $param['data'] = array(
            'keyword1'=>array('value'=>$types[$tmpData['type']],'color'=>"#173177"),
            'keyword2'=>array('value'=>$applyData['node_name'],'color'=>"#173177"),
            'keyword3'=>array('value'=>$applyData['approver_name'],'color'=>"#173177"),
            'keyword4'=>array('value'=>$applyData['statusStr'],'color'=>"#173177"),
        );

        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }
    public function sendApprovalResultMsg ($receiver,$applyData,$is_sendWxMsg=false){
        $data['appid'] = get_app_info()['appid'];
        $data['type'] = 2 + $applyData['type']; // 财务报销
        $data['emp_id'] = $receiver;
        $data['time'] = NOW_TIME;
        $data['is_read'] = 0;
        $data['reply'] = 0;
        $data['content'] = '审批结果消息';
        $id = $this->add($data);

        if ($id !== false){
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendApprovalResultWxMsg($usr_emp['openid'],$applyData,$formid);
                        }
                    }
                }
            }
        }
    }

    private function sendApprovingWxMsg($openid,$applyData,$formId) {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $types = [' ','加班审批','休假审批','报销审批'];

        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[3];
        $param ['form_id'] = $formId;
        $tmpData = D('OaApplicationView')->where(array('id'=>$applyData['id']))->find();
        if ($tmpData === false) {
            // $param ['page'] = '/pages/task/index';
            $param ['page'] = 'pages/index/index';
        }else{
            // $param ['page'] = '/pages/reimburse/approvaldetails?readonly=false&comment=false&data='.json_encode($tmpData);
            $param ['page'] = 'pages/index/index';
        }

        $param['data'] = array(
            'keyword1'=>array('value'=>$tmpData['apply_no'],'color'=>"#173177"),
            'keyword2'=>array('value'=>$types[$tmpData['type']],'color'=>"#173177"),
            'keyword3'=>array('value'=>$tmpData['dept_name'],'color'=>"#173177"),
            'keyword4'=>array('value'=>$tmpData['emp_name'],'color'=>"#173177"),
        );

        // var_dump($param);
        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }

    public function sendApprovingMsg($receiver,$applyData,$is_sendWxMsg=false){
        $data['appid'] = get_app_info()['appid'];
        $data['type'] = 2 + $applyData['type']; // 财务报销
        $data['emp_id'] = $receiver;
        $data['time'] = NOW_TIME;
        $data['is_read'] = 0;
        $data['reply'] = 0;
        $data['content'] = '新待审批消息';
        $id = $this->add($data);

        if ($id !== false){
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendApprovingWxMsg($usr_emp['openid'],$applyData,$formid);
                        }
                    }
                }
            }
        }
    }

    private function sendAnnoucementWxMsg($openid,$content,$formId,$is_sendWxMsg=false){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[0];
        $param ['form_id'] = $formId;
        $tmpData = D('OaEmpMsgNoticeView')->where(array('id'=>$content['msgid']))->find();
        if ($tmpData === false) {
            // $param ['page'] = '/pages/notice/index';
            $param ['page'] = 'pages/index/index';
        }else{
            // $param ['page'] = '/pages/notice/detail?data='.json_encode($tmpData);
            $param ['page'] = 'pages/index/index';
        }

        $param['data'] = array(
            'keyword1'=>array('value'=>$content['title'],'color'=>"#173177"),
            'keyword2'=>array('value'=>$content['time'],'color'=>"#173177"),
        );

        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }
    public function sendAnnoucementMsg($receiver,$time,$content,$noticid,$is_sendWxMsg) {
        $data['appid'] = get_app_info()['appid'];
        $data['noticeid'] = $noticid;
        $data['type'] = 0;
        $data['emp_id'] = $receiver;
        $data['time'] = $time;
        $data['is_read'] = 0;
        $id = $this->add($data);
        if ($id !== false){
            $content['msgid'] = $id;
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendAnnoucementWxMsg($usr_emp['openid'],$content,$formid);
                        }
                    }
                }
            }
        }
    }
    private function sendNoticeWxMsg($openid,$content,$formId,$is_sendWxMsg=false){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[1];
        $param ['form_id'] = $formId;
        $tmpData = D('OaEmpMsgNoticeView')->where(array('id'=>$content['msgid']))->find();
        if ($tmpData === false) {
            // $param ['page'] = '/pages/notice/index';
            $param ['page'] = 'pages/index/index';
        }else{
            // $param ['page'] = '/pages/notice/detail?data='.json_encode($tmpData);
            $param ['page'] = 'pages/index/index';
        }
        $titles =  explode(';',$content['title']);
        $param['data'] = array(
            'keyword1'=>array('value'=>$titles[0],'color'=>"#173177"),
            'keyword2'=>array('value'=>$titles[1],'color'=>"#173177"),
            'keyword3'=>array('value'=>$titles[2],'color'=>"#173177"),
            'keyword4'=>array('value'=>'请及时确认参加会议','color'=>"#173177"),
        );

        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }
    public function sendNoticeMsg($receiver,$time,$content,$noticeid,$is_sendWxMsg) {
        $data['appid'] = get_app_info()['appid'];
        $data['noticeid'] = $noticeid;
        $data['type'] = 1;
        $data['emp_id'] = $receiver;
        $data['time'] = $time;
        $data['is_read'] = 0;
        $data['reply'] = 0;
        $map['noticeid'] = $noticeid;
        $map['emp_id'] = $receiver;
        $res = M('OaEmpMsg')->where($map)->find();
        if(!empty($res)){
            $data['id'] = $res['id'];
            $this->save($data);
            $id = $res['id'];
        }else{
            $id = $this->add($data);
        }
        if ($id !== false){
            $content['msgid'] = $id;
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendNoticeWxMsg($usr_emp['openid'],$content,$formid);
                        }
                    }
                }
            }
        }
    }

    private function sendSupperviseWxMsg($openid,$content,$formId,$is_sendWxMsg=false){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[2];
        $param ['form_id'] = $formId;
        $tmpData = D('OaNoticeTaskReplyNoticeView')->where(array('noticeid'=>$content['id'],'pid'=>0,'receiver'=>$content['creater']))->find();
        if ($tmpData === false) {
            // $param ['page'] = '/pages/notice/index';
            $param ['page'] = 'pages/index/index';
        }else{
            // $param ['page'] = '/pages/notice/suppervise?data='.json_encode($tmpData);
            $param ['page'] = 'pages/index/index';
        }

        $param['data'] = array(
            'keyword1'=>array('value'=>$content['from_who'],'color'=>"#173177"),
            'keyword2'=>array('value'=>$content['title'],'color'=>"#173177"),
            'keyword3'=>array('value'=>$content['receivername'],'color'=>"#173177"),
            );

        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }

    public function sendSupperviseMsg($receiver,$noticeData,$is_sendWxMsg) {
        $data['appid'] = get_app_info()['appid'];
        $data['noticeid'] = $noticeData['id'];
        $data['type'] = 2;
        $data['emp_id'] = $receiver;
        $data['time'] = $noticeData['time'];
        $data['is_read'] = 1;
        $data['reply'] = 0;

        $map['noticeid'] =  $noticeData['id'];
        $map['emp_id'] = $receiver;
        $res = M('OaEmpMsg')->where($map)->find();
        if(!empty($res)){
            $data['id'] = $res['id'];
            $this->save($data);
            $id = $res['id'];
        }else{
            $id = $this->add($data);
        }

        $content = $noticeData;
        $content['receivername'] = M('OaEmployee')->where(array('id'=>$receiver))->getField('name');
        if ($id !== false){
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendSupperviseWxMsg($usr_emp['openid'],$content,$formid);
                        }
                    }
                }
            }
        }
    }
    private function sendLogisticsServiceWxMsg($openid,$content,$formId) {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[5];
        $param ['form_id'] = $formId;
        $param ['page'] = 'pages/index/index';

        if ($content['type'] == 1) {
            $date = date('Y/m/d', $content['date']);
            $name = $content['name'];
        } else {
            $date = date('Y/m/d', NOW_TIME);
            $name =$content['brand'].$content['name'].$content['description'];
        }
        $comment = '您预订商品已被确认';
        $param['data'] = array(
            'keyword1'=>array('value'=>$name,'color'=>"#173177"),
            'keyword2'=>array('value'=>$date,'color'=>"#173177"),
            'keyword3'=>array('value'=>$content['price'].'元','color'=>"#173177"),
            'keyword4'=>array('value'=>$comment,'color'=>"#173177"),
        );
        // var_dump('sendLogisticsServiceWxMsg:'.$param ['template_id']);
        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }
    public function sendLogisticServiceMsg($receiver,$content,$is_sendWxMsg) {
        $empset = M('OaEmpset')->where(array('emp_id'=>$receiver))->find();
        if (($empset['dining_msg'] != 1) && ($content['type'] == 1)){
            // 食堂订阅消息关闭
            return;
        }
        if (($empset['grocery_msg'] != 1) && ($content['type'] == 2)){
            // 小卖部订阅消息关闭
            return;
        }
        $typeStr = ['食堂','小卖部'];
        $data['appid'] = get_app_info()['appid'];
        $data['type'] = 6 + $content['type'];
        $data['emp_id'] = $receiver;
        $data['time'] = NOW_TIME;
        $data['is_read'] = 0;
        $data['reply'] = 0;
        $data['content'] = $typeStr[$content['type']-1].'预订确认消息';
        $id = $this->add($data);
        if ($id !== false){
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendLogisticsServiceWxMsg($usr_emp['openid'],$content,$formid);
                        }
                    }
                }
            }
        }
    }
    private function sendServiceOrderWxMsg($openid,$content,$formId) {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_access_token ();
        $param ['touser'] = $openid;
        $param ['template_id'] = $this->template_ids[6];
        $param ['form_id'] = $formId;
        $param ['page'] = 'pages/index/index';

        if ($content['type'] == 1) {
            $date = date('Y/m/d', $content['time']);
            $name = $content['name'];
        } else {
            $date = date('Y/m/d', $content['time']);
            $name =$content['brand'].$content['name'].$content['description'];
        }
        // $comment = '您的订单已生成';
        $param['data'] = array(
            'keyword1'=>array('value'=>$name,'color'=>"#173177"),
            'keyword2'=>array('value'=>$content['price'].'元','color'=>"#173177"),
            'keyword3'=>array('value'=>$content['emp_name'],'color'=>"#173177"),
            'keyword4'=>array('value'=>$date,'color'=>"#173177"),
        );

        $res = post_data ( $url, $param );
        if($res['errcode'] !== 0) {
            // var_dump($res);
            return $res;
        }
        return true;
    }
    public function sendServiceOrderMsg($receiver,$content,$is_sendWxMsg) {
        $empset = M('OaEmpset')->where(array('emp_id'=>$receiver))->find();
        if (($empset['dining_msg'] != 1) && ($content['type'] == 1)){
            // 食堂订阅消息关闭
            return;
        }
        if (($empset['grocery_msg'] != 1) && ($content['type'] == 2)){
            // 小卖部订阅消息关闭
            return;
        }
        $typeStr = ['食堂','小卖部'];
        $data['appid'] = get_app_info()['appid'];
        $data['type'] = 6 + $content['type'];
        $data['emp_id'] = $receiver;
        $data['time'] = NOW_TIME;
        $data['is_read'] = 0;
        $data['reply'] = 0;
        $data['content'] = $typeStr[$content['type']-1].'预订创建消息';
        $id = $this->add($data);
        if ($id !== false){
            if($is_sendWxMsg === true) {
                $usr_emps = M('OaUserEmployee')->where(array('emp_id'=>$receiver))->select();
                foreach ($usr_emps as $usr_emp) {
                    if(!empty($usr_emp['openid'])){
                        $formid = $this->get_wxFormid($usr_emp['openid']);
                        if(!empty($formid)){
                            $this->sendServiceOrderWxMsg($usr_emp['openid'],$content,$formid);
                        }
                    }
                }
            }
        }
    }

}